﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using C4F.DevKit.Contacts.Data;

namespace C4F.DevKit.Contacts.Samples.Win
{
    public partial class ContactDBList : Form
    {
        #region Private Data

        SimpleContactDataSet _simpleContacts = null;

        #endregion Private Data

        #region Constants

        private const int CONTACTID_COLUMN_INDEX = 0;
        private const int FIRSTNAME_COLUMN_INDEX = 1;
        private const int MIDDLENAME_COLUMN_INDEX = 2;
        private const int LASTNAME_COLUMN_INDEX = 3;
        
        private const string CONTACTID_COLUMN_SOURCE = "ContactID";
        private const string FIRSTNAME_COLUMN_SOURCE = "FirstName";
        private const string MIDDLE_COLUMN_SOURCE = "MiddleName";
        private const string LASTNAME_COLUMN_SOURCE = "LastName";

        #endregion Constants

        #region Properties

        public Guid ContactID
        {
            get
            {
                if (dgContactList.SelectedRows.Count < 1)
                    return Guid.Empty;
                else
                    return new Guid(dgContactList.SelectedRows[0].Cells[CONTACTID_COLUMN_INDEX].Value.ToString());
            }
        }

        #endregion Properties

        #region Constructors

        public ContactDBList()
        {
            InitializeComponent();            

            try
            {
                _simpleContacts = contactsService1.GetSimpleContactsFromDatabase();                
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }

        #endregion Constructors
        
        #region Methods

        #region EventHandlers

        private void ContactDBList_Load(object sender, EventArgs e)
        {
            InitializeBinding();
        }

        #endregion EventHandlers

        #region Private 

        private void DisplayException(Exception ex)
        {
            if (ex != null)
                MessageBox.Show(ex.ToString());
        }

        private void InitializeBinding()
        {
            if (_simpleContacts != null)
            {
                bindingSource1.DataSource = _simpleContacts;
                bindingSource1.DataMember = "SimpleContact";

                dgContactList.Columns[CONTACTID_COLUMN_INDEX].DataPropertyName = CONTACTID_COLUMN_SOURCE;
                dgContactList.Columns[FIRSTNAME_COLUMN_INDEX].DataPropertyName = FIRSTNAME_COLUMN_SOURCE;
                dgContactList.Columns[MIDDLENAME_COLUMN_INDEX].DataPropertyName = MIDDLE_COLUMN_SOURCE;
                dgContactList.Columns[LASTNAME_COLUMN_INDEX].DataPropertyName = LASTNAME_COLUMN_SOURCE;
            }
        }

        #endregion Private

        #endregion Methods
    }
}
